#include <iostream>
#include <vector>
using namespace std;

class Solution {
    vector<int> ret;
    vector<int> tmpnums;
    vector<int> tmpIndex;
    vector<int> Index;

public:
    vector<int> countSmaller(vector<int>& nums) {
        int n = nums.size();

        ret.resize(n);
        Index.resize(n);
        tmpIndex.resize(n);
        tmpnums.resize(n);
        for (int i = 0; i < n; i++) {
            Index[i] = i;
        }

        mergeSort(nums, 0, n - 1);
        return ret;
    }

    void mergeSort(vector<int>& nums, int start, int end) {
        if (start >= end)
            return;

        int mid = (start + end) / 2;

        mergeSort(nums, start, mid);
        mergeSort(nums, mid + 1, end);

        int cur1 = start, cur2 = mid + 1, i = 0;
        while (cur1 <= mid && cur2 <= end) {
            if (nums[cur1] > nums[cur2]) {
                ret[Index[cur1]] += (end - cur2 + 1);
                tmpnums[i] = nums[cur1];
                tmpIndex[i++] = Index[cur1++];
            }
            else {
                tmpnums[i] = nums[cur2];
                tmpIndex[i++] = Index[cur2++];
            }
        }

        while (cur1 <= mid) {
            tmpIndex[i] = Index[cur1];
            tmpnums[i++] = nums[cur1++];
        }

        while (cur2 <= end) {
            tmpIndex[i] = Index[cur2];
            tmpnums[i++] = nums[cur2++];
        }

        for (int j = start; j <= end; j++) {
            nums[j] = tmpnums[j - start];
            Index[j] = tmpIndex[j - start];
        }
    }
};


int main()
{
    vector<int>nums = { 5, 2, 6, 1 };
    vector<int>ret = Solution().countSmaller(nums);
    for (auto a : ret)
    {
        cout << a << ' ';
    }
    cout << endl;
    return 0;
}